/*
 * ./src/fonction_threads.c
 * Copyright (C) 2009 Lameire Alexis
 * 
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "fonction_threads.h"

void *timeout(void *data)
{
	donnee_timeout *donnee_prog = (donnee_timeout *) data;

	printf(_("DEBUG : Sleep thread : %d s\n"), donnee_prog->jeux->config_prog->temps_timeout);
	sleep(donnee_prog->jeux->config_prog->temps_timeout);
	if (donnee_prog->compteur_mot == donnee_prog->jeux->compteur_mot)
	{
		donnee_prog->jeux->timeout = 1;
		cmd_passer(donnee_prog->jeux, donnee_prog->origin, donnee_prog->session, NULL, 0);
	}

	free(donnee_prog->origin);
	free(donnee_prog);
}

void init_thread_timeout(donnee_de_control * jeux, const char *origin, irc_session_t * session)
{
	donnee_timeout *donnee_thread = NULL;
	int taille_origin = strlen(origin);

	char *cpy_origin = malloc(sizeof(char) * (taille_origin + 1));
	donnee_thread = malloc(sizeof(donnee_timeout));


	if (donnee_thread == NULL || cpy_origin == NULL)
	{
		fprintf(stderr, _("ERREUR : Impossible d'initialiser la structure de thread"));
	}
	else
	{
		pthread_t thread;

		jeux->compteur_mot++;
		strcpy(cpy_origin, origin);
		donnee_thread->compteur_mot = jeux->compteur_mot;
		donnee_thread->origin = cpy_origin;
		donnee_thread->jeux = jeux;
		donnee_thread->session = session;

		pthread_create(&thread, NULL, timeout, donnee_thread);
	}
}
